from sqlalchemy.orm import Session

from controller.PublicAdminController import PublicAdminController
from controller.UserAdminController import UserAdminController
from crud import EmployeeAdminCrud
from schema.ParamSchema import UserInfo
from schema.QuerySchema import QueryBase, EmployeeQuery
from schema.TeachingSchema import EmployeeInfo
from util.EmailHelper import EmailHelper
from util.ErrorCode import ErrorCode


class EmployeeAdminController:

    @staticmethod
    def add_employee(employeeInfo: EmployeeInfo, db: Session, ):
        if PublicAdminController.check_phone_num(employeeInfo.phone):
            response = EmployeeAdminCrud.add_employee(employeeInfo, db)
            if response.get('code') == 0:
                password = PublicAdminController.generate_password()
                userInfo = UserInfo(user_id=employeeInfo.phone, port_id=employeeInfo.port, user_name=employeeInfo.name,
                                    password=password, status=1)
                response = UserAdminController.add_user(userInfo, db)
                if response.get('code') == 0:
                    if EmailHelper.sendEmail(employeeInfo.email, '', '用户创建成功通知',
                                             f'用户名:{employeeInfo.phone}\n密码:{password}'):
                        return {'code': ErrorCode.SUCCESS.value, 'message': 'success'}
                    else:
                        return {'code': ErrorCode.SEND_EMAIL_ERROR.value,
                                'message': 'create user success! but sendemail failed! please contact administrator!'}
                else:
                    return {'code': ErrorCode.CREATE_USER_FAILED.value,
                            'message': 'create user failed! please contact administrator!'}
            else:
                return response
        else:
            return {"code": ErrorCode.PHONE_FORMAT_INVALID.value, "message": "phone格式非法"}

    @staticmethod
    def mod_employee(employeeInfo: EmployeeInfo, db: Session):
        employeeModel = EmployeeAdminCrud.mod_employee(employeeInfo, db)
        modUserFlag = False
        if employeeModel is not None:
            userInfo = UserInfo(user_id=employeeModel.phone)
            if employeeInfo.port != 0:
                userInfo.port_id = employeeInfo.port
                modUserFlag = True
            if employeeInfo.status != 0:
                userInfo.status = employeeInfo.status
                modUserFlag = True
            if employeeInfo.name is not None:
                if len(employeeInfo.name) != 0:
                    userInfo.user_name = employeeInfo.name
                    modUserFlag = True
            if modUserFlag:
                response = UserAdminController.mod_user(userInfo, db)
                if response.get('code') == 0:
                    return response
                else:
                    return {'code': ErrorCode.EMPLOYEE_MOD_SUCCESS_BUT_USER_MOD_FAILED.value,
                            'message': 'employee mod success,but user mod failed! please contact administrator!'}
            else:
                return {'code': ErrorCode.SUCCESS.value, 'message': 'success'}
        else:
            return {'code': ErrorCode.DATABASE_ERROR.value, 'message': 'database error or record not exists!'}

    @staticmethod
    def query_employee_by_field(employeeQuery: EmployeeQuery, db: Session):
        return EmployeeAdminCrud.query_employee_by_field(employeeQuery, db)

    @staticmethod
    def query_employee_by_port_id(port_id: int, db: Session):
        return EmployeeAdminCrud.query_employee_by_port_id(port_id, db)

    @staticmethod
    def query_employee_all_group_by_port(db: Session):
        response = EmployeeAdminCrud.query_employee_all_group_by_port(db)
        result = []

        if response.get('code') == 0:
            data = response.get('data')
            current_port_id = None
            current_dict_data = None
            if data is not None:
                for r in data:
                    if current_port_id != r[0]:
                        if current_dict_data is not None:
                            result.append(current_dict_data)
                        current_port_id = r[0]
                        current_dict_data = {'value': r[0], 'label': r[1], 'children': [{'value': r[2], 'label': r[3]}]}
                    else:
                        current_dict_data['children'].append({'value': r[2], 'label': r[3]})
                result.append(current_dict_data)
            return {'code': ErrorCode.SUCCESS.value, 'message': 'success!', 'data': result}


        else:
            return response

    @staticmethod
    def query_employee_by_page(query_base: QueryBase, db: Session):
        return EmployeeAdminCrud.query_employee_by_page(query_base, db)

